let express=require("express")();
let expressStatic=require("express-static");
let mysql=require("mysql");
const port=83;
// 规划一个数据库连接
let sql=mysql.createConnection({
	host:"localhost",
	user:"root",
	password:"123456",
	database:"sms",
	timezone : "08:00"
});
// 尝试连接数据库
sql.connect();
express.get("/getuser",(request,response)=>{
	sql.query(`SELECT * FROM student`,(error,data)=>{
		if(error){
			response.send("error")
			console.log(error)
		}
		else{
			response.send(data)
			console.log(data)
		}
	})
})
express.get("/deleteStudent",(request,response)=>{
	sql.query(`DELETE FROM student WHERE id=${request.query.id}`,(error,data)=>{
		if(error){
			console.log(error)
			response.send("error")
		}
		else{
			response.send("success")
		}
	})
})
express.get("/addStudent",(request,response)=>{
	let p = request.query;
	sql.query(`INSERT INTO student (name,age,sex,city,joinDate) VALUES ("${p.name}","${p.age}","${p.sex}","${p.city}","${p.joinDate}")`,(error,data)=>{
		if(error){
			console.log(error)
			response.send("error")
		}
		else{
			response.send("success")
			console.log(`新增学生${p.name}操作成功`)
		}
	})
})

express.get("/editStudent",(request,response)=>{
	let q= request.query;
	sql.query(	`UPDATE student SET name="${q.name}",age="${q.age}",sex="${q.sex}",city="${q.city}",date="${q.date}" WHERE id="${q.id}")`,(error,data)=>{
		if(error){
			console.log(error)
			response.send("error")
		}
		else{
			response.send("success")
			console.log(`修改学生${q.name}操作成功`)
		}
	})
})
express.get("/login",(request,response)=>{
	let r= request.query;
	// console.log(r)
	sql.query(	`SELECT * FROM user WHERE username="${r.username}" AND password="${r.password}"`,(error,data)=>{
		if(error){
			console.log(error)
			response.send("3")
		}
		else{
			if(data.length === 0){
			response.send("2")
		}
		else{
			response.send(JSON.stringify(data))
			console.log(data)
		}
		
		}
	})
})
express.get("/register",(request,response)=>{
		sql.query(`INSERT INTO user (username,password，name) VALUES ("${request.query.username}","${request.query.password}","${request.query.name}")`,(error,data)=>{
				if(error){
					response.send("error");
					console.log(error);
				}
				else{
					response.end("success");
					console.log(data)
				}
		})
	})
express.get("/",(request,response)=>{
	response.send("success")
})
// 如果接收到来自前端的静态文件请求的话,我该去哪里找
express.use(expressStatic(__dirname + `/static`))
console.log(`running at ${port}`)
express.listen(port)